import router from './router'
import store from './store'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import { setToken, getToken, canTurnTo } from '@/libs/util'
import getPageTitle from '@/utils/get-page-title'
import settings from '@/settings'
import { constantRoutes } from '@/router'
const { homeName } = settings

NProgress.configure({ showSpinner: false }) // NProgress Configuration
const LOGIN_PAGE_NAME = 'login'
const USER_REGISTER_NAME = 'userRegister'
const ORG_REGISTER_NAME = 'orgRegister'
const RESET_PASSWORD_NAME = 'resetPassword'
const whitePath = ['realTimeVideo', 'modelingThreeD', 'waringMap']

const turnTo = (to, routers, next) => {
  if (canTurnTo(to.name, routers)) next() // 有权限，可访问
  else next({ replace: true, name: '401' }) // 无权限，重定向到401页面
}
router.beforeEach(async(to, from, next) => {
  // start progress bar
  NProgress.start()

  // set page title
  document.title = getPageTitle(to.meta.title)

  // determine whether the user has logged in
  const token = getToken()
  if (!token && to.name === USER_REGISTER_NAME) {
    turnTo(to, store.state.user.routers, next) // 用户注册,郭静添加
  } else if (!token && to.name === ORG_REGISTER_NAME) {
    turnTo(to, store.state.user.routers, next) // 单位注册,郭静添加
  } else if (!token && to.name === RESET_PASSWORD_NAME) {
    turnTo(to, store.state.user.routers, next) // 密码重置
  } else if (!token && whitePath.indexOf(to.name) > -1) {
    turnTo(to, store.state.user.routers, next) // 白名单
  } else if (!token && to.name !== LOGIN_PAGE_NAME) {
    // 未登录且要跳转的页面不是登录页
    next({ name: LOGIN_PAGE_NAME // 跳转到登录页
    })
  } else if (!token && to.name === LOGIN_PAGE_NAME) {
    // 未登陆且要跳转的页面是登录页
    next() // 跳转
  } else if (token && to.name === LOGIN_PAGE_NAME) {
    // 已登录且要跳转的页面是登录页
    next({
      name: homeName // 跳转到homeName页
    })
  } else {
    if (store.state.user.hasGetInfo) {
      turnTo(to, store.state.user.routers, next)
    } else {
      store.dispatch('user/getUserInfo').then(user => {
        // 拉取用户信息，通过用户权限和跳转的页面的name来判断是否有权限访问;
        const getRoutename = (list, path, route, next) => {
          const len = list.length
          let i = 0
          while (i < len) {
            if (list[i].children && list[i].children.length) {
              getRoutename(list[i].children, path, route, next)
            } else {
              if (list[i].path === path || ('/' + list[i].path) === path) {
                route.replace({
                  name: list[i].name
                })
                next()
                break
              }
            }
            i++
          }
        }
        getRoutename(constantRoutes, to.path, router, next)
      }).catch(() => {
        setToken('')
        next({
          name: 'login'
        })
      })
    }
  }
})

router.afterEach(() => {
  // finish progress bar
  NProgress.done()
})
